/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wisnu.scs.controller;

import com.wisnu.scs.add.DateFactory;
import com.wisnu.scs.error.ErrorMessage;
import com.wisnu.scs.model.DbBarangModel;
import com.wisnu.scs.report.model.DbBarangRekap;
import com.wisnu.scs.view.DbBarangView;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Wisnu Wardoyo
 */
public class DbBarangController {

    private DbBarangModel model;

    public void setBarangModel(DbBarangModel barangModel) {
        this.model = barangModel;
    }

    public void resetForm() {
        model.resetForm();
    }

    public void insertBarang(DbBarangView view) {
        String namaBarang = view.getTxtNamaBarang().getText();
        String stock = view.getTxtStock().getText();

        if (namaBarang.trim().equals("")) {
            JOptionPane.showMessageDialog(view, "Nama Barang Masih Kosong");
        } else if (namaBarang.length() > 255) {
            JOptionPane.showMessageDialog(view, "Nama Barang Tidak Boleh Lebih dari 255 Karakter");
        } else if (stock.trim().equals("")) {
            JOptionPane.showMessageDialog(view, "Stock Masih Kosong");
        } else {
            int stockInt = 0;
            try {
                stockInt = Integer.parseInt(stock);
            } catch (NumberFormatException exception) {
                JOptionPane.showMessageDialog(view, "Stock Harus Angka!");
                return;
            }

            model.setNamaBarang(namaBarang);
            model.setStock(stockInt);
            try {
                model.insertBarang();
                JOptionPane.showMessageDialog(view, "Data berhasil ditambah");
                model.resetForm();
            } catch (ErrorMessage ex) {
                JOptionPane.showMessageDialog(view, new Object[]{
                    "Terjadi error pada database dengan pesan :",
                    ex.getMessage()
                });
            }

        }

    }

    public void updateBarang(DbBarangView view) {
        if (view.getTableBarang().getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(view, "Silahkan seleksi baris yang akan diubah");
            return;
        }

        Integer id = Integer.parseInt(view.getTxtId().getText());
        String namaBarang = view.getTxtNamaBarang().getText();
        String stock = view.getTxtStock().getText();

        if (namaBarang.trim().equals("")) {
            JOptionPane.showMessageDialog(view, "Nama Barang Masih Kosong");
        } else if (namaBarang.length() > 255) {
            JOptionPane.showMessageDialog(view, "Nama Barang Tidak Boleh Lebih dari 255 Karakter");
        } else if (stock.trim().equals("")) {
            JOptionPane.showMessageDialog(view, "Stock Masih Kosong");
        } else {
            int stockInt = 0;
            try {
                stockInt = Integer.parseInt(stock);
            } catch (NumberFormatException exception) {
                JOptionPane.showMessageDialog(view, "Stock Harus Angka!");
                return;
            }

            model.setId(id);
            model.setNamaBarang(namaBarang);
            model.setStock(stockInt);
            try {
                model.updateBarang();
                JOptionPane.showMessageDialog(view, "Data berhasil diubah");
                model.resetForm();
            } catch (ErrorMessage ex) {
                JOptionPane.showMessageDialog(view, new Object[]{
                    "Terjadi error pada database dengan pesan :",
                    ex.getMessage()
                });
            }

        }

    }

    public void deleteBarang(DbBarangView view) {
        if (view.getTableBarang().getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(view, "Silahkan seleksi baris yang akan diubah");
            return;
        }

        if (JOptionPane.showConfirmDialog(view, "Anda yakin akan menghapus?") == JOptionPane.OK_OPTION) {
            Integer id = Integer.parseInt(view.getTxtId().getText());
            String namaBarang = view.getTxtNamaBarang().getText();
            String stock = view.getTxtStock().getText();
            model.setId(id);
            model.setNamaBarang(namaBarang);
            model.setStock(Integer.parseInt(stock));
            try {
                model.deleteBarang();
                JOptionPane.showMessageDialog(view, "Barang berhasil dihapus");
                model.resetForm();
            } catch (ErrorMessage error) {
                JOptionPane.showMessageDialog(view, new Object[]{
                    "Terjadi error di database dengan pesan :",
                    error.getMessage()
                });
            }
        }
    }

    public void searchBarang(DbBarangView view) {
        String searchText = view.getTxtSearchBox().getText();
        Date fisrtDate = new Date();
        Date lastDate = new Date();
        try {
            fisrtDate = (Date) view.getTxtFirstDate().getValue();
            lastDate = (Date) view.getTxtLastDate().getValue();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(view, "Format tanggal salah, silahkan reset");
        }
        if (!searchText.trim().equals("")) {
            model.setSearchText(searchText);
            if (view.getRadioByDate().isSelected()) {
                model.setFirstDate(fisrtDate);
                try {
                    model.searchBarangByDate();
                    view.setPeriod(searchText);
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }

            } else if (view.getRadioByMonth().isSelected() == true) {
                model.setListDate(DateFactory.getMonthOfDay(fisrtDate));
                try {
                    model.searchBarangByMonth();
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }
            } else if (view.getRadioByRange().isSelected()) {
                if (fisrtDate.after(lastDate)) {
                    JOptionPane.showMessageDialog(view, "Tanggal Awal tidak boleh lebih dari tanggal akhir");
                    model.resetForm();

                } else {
                    List<Date> listDate = new ArrayList<>();
                    listDate.add(fisrtDate);
                    listDate.add(lastDate);
                    model.setListDate(listDate);
                    System.out.println("range");
                    try {
                        model.searchBarangByDateRange();
                    } catch (ErrorMessage ex) {
                        JOptionPane.showMessageDialog(view, new Object[]{
                            "Terjadi error pada database dengan pesan :",
                            ex.getMessage()
                        });
                    } finally {
                        model.resetForm();
                    }
                }

            } else {
                try {
                    model.searchBarang();
                    System.out.println("Key");
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }
            }
        } else {
            if (view.getRadioByDate().isSelected()) {
                model.setFirstDate(fisrtDate);
                try {
                    model.searchBarangByDate2();
                    System.out.println("Date 2");
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }

            } else if (view.getRadioByMonth().isSelected() == true) {
                model.setListDate(DateFactory.getMonthOfDay(fisrtDate));
                try {
                    model.searchBarangByDateRange2();
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }
            } else if (view.getRadioByRange().isSelected()) {
                if (fisrtDate.after(lastDate)) {
                    JOptionPane.showMessageDialog(view, "Tanggal Awal tidak boleh lebih dari tanggal akhir");
                    model.resetForm();

                } else {
                    List<Date> listDate = new ArrayList<>();
                    listDate.add(fisrtDate);
                    listDate.add(lastDate);
                    model.setListDate(listDate);
                    System.out.println("range");
                    try {
                        model.searchBarangByDateRange2();
                    } catch (ErrorMessage ex) {
                        JOptionPane.showMessageDialog(view, new Object[]{
                            "Terjadi error pada database dengan pesan :",
                            ex.getMessage()
                        });
                    } finally {
                        model.resetForm();
                    }
                }

            } else {
                try {
                    model.setSearchText("");
                    model.searchBarang();
                    System.out.println("Key");
                } catch (ErrorMessage ex) {
                    JOptionPane.showMessageDialog(view, new Object[]{
                        "Terjadi error pada database dengan pesan :",
                        ex.getMessage()
                    });
                } finally {
                    model.resetForm();
                }
            }
        }
        model.setId(0);
        model.setNamaBarang("");
        model.setStock(0);

    }

    public void print(DbBarangView view) {
        try {
            String reportName = "./report/com/wisnu/scs/report/DbRekapReport.jrxml";
            JasperDesign jasperDesign = JRXmlLoader.load(reportName);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            Map map = new HashMap();
            //map.put("Periode", view.getPeriod());
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,
                    new JRBeanCollectionDataSource(
                            getDataTable(view)));
            JasperViewer.viewReport(jasperPrint, false);
        } catch (JRException ex) {
            Logger.getLogger(DbBarangController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected List<Object> getDataTable(DbBarangView view) {
        List<Object> object = new LinkedList<>();

        for (int i = 0; i < view.getTableBarang().getRowCount(); i++) {
            DbBarangRekap barangRekap = new DbBarangRekap();
            barangRekap.setNamaBarang((String) view.getTableBarang().getValueAt(i, 1));
            barangRekap.setJumlahMasuk((Integer)view.getTableBarang().getValueAt(i, 2));
            barangRekap.setJumlahKeluar((Integer)view.getTableBarang().getValueAt(i, 3));
            barangRekap.setStock(String.valueOf(view.getTableBarang().getValueAt(i, 3)));
            object.add(barangRekap);
        }
        return object;

    }
}
